using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CKY.AgentPlatform.ModelConfigs
{
    /// <summary>
    /// 模型适配器注册表
    /// </summary>
    public class ModelAdapterRegistry
    {
        private readonly Dictionary<ModelProvider, List<IModelInvocationAdapter>> _adapters = new();
        private readonly Dictionary<ModelApiMode, List<IModelInvocationAdapter>> _modeAdapters = new();
        private readonly List<ModelProviderRegistration> _providerRegistrations = new();

        /// <summary>
        /// 注册适配器
        /// </summary>
        /// <param name="adapter">适配器实例</param>
        public void RegisterAdapter(IModelInvocationAdapter adapter)
        {
            if (adapter == null)
                throw new ArgumentNullException(nameof(adapter));

            // 按提供商分组
            if (!_adapters.ContainsKey(adapter.SupportedProvider))
            {
                _adapters[adapter.SupportedProvider] = new List<IModelInvocationAdapter>();
            }
            _adapters[adapter.SupportedProvider].Add(adapter);

            // 按API模式分组
            if (!_modeAdapters.ContainsKey(adapter.SupportedMode))
            {
                _modeAdapters[adapter.SupportedMode] = new List<IModelInvocationAdapter>();
            }
            _modeAdapters[adapter.SupportedMode].Add(adapter);
        }

        /// <summary>
        /// 注册提供商
        /// </summary>
        /// <param name="registration">提供商注册信息</param>
        public void RegisterProvider(ModelProviderRegistration registration)
        {
            if (registration == null)
                throw new ArgumentNullException(nameof(registration));

            _providerRegistrations.Add(registration);
        }

        /// <summary>
        /// 获取指定提供商的适配器
        /// </summary>
        /// <param name="provider">模型提供商</param>
        /// <param name="apiMode">API模式</param>
        /// <returns>适配器实例</returns>
        public IModelInvocationAdapter GetAdapter(ModelProvider provider, ModelApiMode apiMode)
        {
            // 首先尝试获取提供商和API模式完全匹配的适配器
            if (_adapters.TryGetValue(provider, out var providerAdapters))
            {
                var exactMatch = providerAdapters.FirstOrDefault(a => a.SupportedMode == apiMode);
                if (exactMatch != null)
                    return exactMatch;
            }

            // 如果没有完全匹配，尝试获取指定API模式的适配器
            if (_modeAdapters.TryGetValue(apiMode, out var modeAdapters))
            {
                var modeMatch = modeAdapters.FirstOrDefault(a => a.SupportedProvider == ModelProvider.Custom || a.SupportedProvider == provider);
                if (modeMatch != null)
                    return modeMatch;
            }

            // 如果是Auto模式，尝试获取提供商的任何适配器
            if (apiMode == ModelApiMode.Auto && _adapters.TryGetValue(provider, out providerAdapters))
            {
                return providerAdapters.FirstOrDefault();
            }

            throw new InvalidOperationException($"未找到适合的适配器: Provider={provider}, ApiMode={apiMode}");
        }

        /// <summary>
        /// 获取指定提供商的所有适配器
        /// </summary>
        /// <param name="provider">模型提供商</param>
        /// <returns>适配器列表</returns>
        public IReadOnlyList<IModelInvocationAdapter> GetAdaptersByProvider(ModelProvider provider)
        {
            return _adapters.TryGetValue(provider, out var adapters)
                ? adapters.AsReadOnly()
                : new List<IModelInvocationAdapter>().AsReadOnly();
        }

        /// <summary>
        /// 获取指定API模式的所有适配器
        /// </summary>
        /// <param name="apiMode">API模式</param>
        /// <returns>适配器列表</returns>
        public IReadOnlyList<IModelInvocationAdapter> GetAdaptersByMode(ModelApiMode apiMode)
        {
            return _modeAdapters.TryGetValue(apiMode, out var adapters)
                ? adapters.AsReadOnly()
                : new List<IModelInvocationAdapter>().AsReadOnly();
        }

        /// <summary>
        /// 获取所有已注册的适配器
        /// </summary>
        /// <returns>适配器列表</returns>
        public IReadOnlyList<IModelInvocationAdapter> GetAllAdapters()
        {
            return _adapters.Values.SelectMany(a => a).Distinct().ToList().AsReadOnly();
        }

        /// <summary>
        /// 获取所有已注册的提供商
        /// </summary>
        /// <returns>提供商列表</returns>
        public IReadOnlyList<ModelProviderRegistration> GetAllProviders()
        {
            return _providerRegistrations.AsReadOnly();
        }

        /// <summary>
        /// 获取指定提供商的注册信息
        /// </summary>
        /// <param name="provider">模型提供商</param>
        /// <returns>提供商注册信息</returns>
        public ModelProviderRegistration GetProviderRegistration(ModelProvider provider)
        {
            return _providerRegistrations.FirstOrDefault(p => p.ProviderType == provider);
        }

        /// <summary>
        /// 检查提供商是否已注册
        /// </summary>
        /// <param name="provider">模型提供商</param>
        /// <returns>是否已注册</returns>
        public bool IsProviderRegistered(ModelProvider provider)
        {
            return _adapters.ContainsKey(provider) || _providerRegistrations.Any(p => p.ProviderType == provider);
        }

        /// <summary>
        /// 检查适配器是否已注册
        /// </summary>
        /// <param name="provider">模型提供商</param>
        /// <param name="apiMode">API模式</param>
        /// <returns>是否已注册</returns>
        public bool IsAdapterRegistered(ModelProvider provider, ModelApiMode apiMode)
        {
            try
            {
                var adapter = GetAdapter(provider, apiMode);
                return adapter != null;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 移除适配器
        /// </summary>
        /// <param name="adapter">适配器实例</param>
        public void RemoveAdapter(IModelInvocationAdapter adapter)
        {
            if (adapter == null)
                return;

            // 从提供商分组中移除
            if (_adapters.TryGetValue(adapter.SupportedProvider, out var providerAdapters))
            {
                providerAdapters.Remove(adapter);
                if (providerAdapters.Count == 0)
                    _adapters.Remove(adapter.SupportedProvider);
            }

            // 从API模式分组中移除
            if (_modeAdapters.TryGetValue(adapter.SupportedMode, out var modeAdapters))
            {
                modeAdapters.Remove(adapter);
                if (modeAdapters.Count == 0)
                    _modeAdapters.Remove(adapter.SupportedMode);
            }
        }

        /// <summary>
        /// 移除提供商注册
        /// </summary>
        /// <param name="provider">模型提供商</param>
        public void RemoveProviderRegistration(ModelProvider provider)
        {
            _providerRegistrations.RemoveAll(p => p.ProviderType == provider);
        }

        /// <summary>
        /// 清空所有注册
        /// </summary>
        public void Clear()
        {
            _adapters.Clear();
            _modeAdapters.Clear();
            _providerRegistrations.Clear();
        }

        /// <summary>
        /// 获取适配器统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        public AdapterRegistryStatistics GetStatistics()
        {
            return new AdapterRegistryStatistics
            {
                TotalAdapters = _adapters.Values.SelectMany(a => a).Distinct().Count(),
                TotalProviders = _providerRegistrations.Count,
                AdaptersByProvider = _adapters.ToDictionary(
                    kvp => kvp.Key,
                    kvp => kvp.Value.Count
                ),
                AdaptersByMode = _modeAdapters.ToDictionary(
                    kvp => kvp.Key,
                    kvp => kvp.Value.Count
                ),
                EnabledProviders = _providerRegistrations.Count(p => p.IsEnabled),
                DisabledProviders = _providerRegistrations.Count(p => !p.IsEnabled)
            };
        }
    }

    /// <summary>
    /// 适配器注册表统计信息
    /// </summary>
    public class AdapterRegistryStatistics
    {
        /// <summary>
        /// 适配器总数
        /// </summary>
        public int TotalAdapters { get; set; }

        /// <summary>
        /// 提供商总数
        /// </summary>
        public int TotalProviders { get; set; }

        /// <summary>
        /// 按提供商分组的适配器数量
        /// </summary>
        public Dictionary<ModelProvider, int> AdaptersByProvider { get; set; } = new();

        /// <summary>
        /// 按API模式分组的适配器数量
        /// </summary>
        public Dictionary<ModelApiMode, int> AdaptersByMode { get; set; } = new();

        /// <summary>
        /// 启用的提供商数量
        /// </summary>
        public int EnabledProviders { get; set; }

        /// <summary>
        /// 禁用的提供商数量
        /// </summary>
        public int DisabledProviders { get; set; }
    }

    /// <summary>
    /// 模型适配器管理器
    /// </summary>
    public class ModelAdapterManager
    {
        private readonly ModelAdapterRegistry _registry;
        private readonly IServiceProvider _serviceProvider;

        public ModelAdapterManager(ModelAdapterRegistry registry, IServiceProvider serviceProvider)
        {
            _registry = registry ?? throw new ArgumentNullException(nameof(registry));
            _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
        }

        /// <summary>
        /// 初始化默认适配器
        /// </summary>
        public void InitializeDefaultAdapters()
        {
            // 注册OpenAI兼容适配器
            var openAICompatibleAdapter = new OpenAICompatibleAdapter();
            _registry.RegisterAdapter(openAICompatibleAdapter);

            // 注册智谱AI原生适配器
            var zhipuNativeAdapter = new ZhipuNativeAdapter();
            _registry.RegisterAdapter(zhipuNativeAdapter);

            // 注册默认提供商配置
            RegisterDefaultProviders();
        }

        /// <summary>
        /// 注册默认提供商
        /// </summary>
        private void RegisterDefaultProviders()
        {
            // 智谱AI提供商注册
            _registry.RegisterProvider(new ModelProviderRegistration
            {
                Name = "智谱AI",
                ProviderType = ModelProvider.ZhipuAI,
                DefaultApiMode = ModelApiMode.Auto,
                DefaultConfig = new ModelInvocationConfig
                {
                    ApiMode = ModelApiMode.Auto,
                    PreferredMode = ModelApiMode.OpenAICompatible,
                    EnableFallback = true,
                    FallbackTimeoutMs = 10000,
                    MaxRetries = 3,
                    Capabilities = ModelProviderCapabilities.Streaming |
                                  ModelProviderCapabilities.FunctionCalling |
                                  ModelProviderCapabilities.JsonMode |
                                  ModelProviderCapabilities.SystemPrompt,
                    SupportedModels = new List<string>
                    {
                        "glm-4", "glm-4-air", "glm-4-airx", "glm-4-flash", "glm-3-turbo"
                    }
                },
                AdapterType = typeof(ZhipuNativeAdapter),
                IsEnabled = true,
                Priority = 90,
                Version = "1.0.0",
                Description = "智谱AI GLM系列模型，支持原生和OpenAI兼容两种API模式"
            });

            // 自定义OpenAI兼容提供商注册
            _registry.RegisterProvider(new ModelProviderRegistration
            {
                Name = "OpenAI兼容提供商",
                ProviderType = ModelProvider.Custom,
                DefaultApiMode = ModelApiMode.OpenAICompatible,
                DefaultConfig = new ModelInvocationConfig
                {
                    ApiMode = ModelApiMode.OpenAICompatible,
                    EnableFallback = false,
                    MaxRetries = 3,
                    Capabilities = ModelProviderCapabilities.Streaming |
                                  ModelProviderCapabilities.FunctionCalling |
                                  ModelProviderCapabilities.JsonMode |
                                  ModelProviderCapabilities.SystemPrompt |
                                  ModelProviderCapabilities.ToolCalling |
                                  ModelProviderCapabilities.Vision
                },
                AdapterType = typeof(OpenAICompatibleAdapter),
                IsEnabled = true,
                Priority = 100,
                Version = "1.0.0",
                Description = "支持所有符合OpenAI API格式的模型提供商"
            });
        }

        /// <summary>
        /// 根据配置自动选择适配器
        /// </summary>
        /// <param name="config">调用配置</param>
        /// <returns>最佳适配器</returns>
        public IModelInvocationAdapter SelectBestAdapter(ModelInvocationConfig config)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            // 如果指定了提供商，尝试获取对应适配器
            if (config.ModelSpecificParams.TryGetValue("Provider", out var providerValue))
            {
                if (Enum.TryParse<ModelProvider>(providerValue.ToString(), out var provider))
                {
                    try
                    {
                        return _registry.GetAdapter(provider, config.ApiMode);
                    }
                    catch
                    {
                        // 如果找不到指定提供商的适配器，继续使用默认逻辑
                    }
                }
            }

            // 根据API模式选择适配器
            if (config.ApiMode == ModelApiMode.Auto)
            {
                // 优先尝试OpenAI兼容模式
                try
                {
                    return _registry.GetAdapter(ModelProvider.Custom, ModelApiMode.OpenAICompatible);
                }
                catch
                {
                    // 回退到原生模式
                    try
                    {
                        return _registry.GetAdapter(ModelProvider.Custom, ModelApiMode.Native);
                    }
                    catch
                    {
                        throw new InvalidOperationException("Auto模式下未找到可用的适配器");
                    }
                }
            }

            // 按指定模式选择适配器
            return _registry.GetAdapter(ModelProvider.Custom, config.ApiMode);
        }

        /// <summary>
        /// 验证适配器配置
        /// </summary>
        /// <param name="config">调用配置</param>
        /// <returns>验证结果</returns>
        public async Task<AdapterValidationResult> ValidateAdapterConfigAsync(ModelInvocationConfig config)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            try
            {
                var adapter = SelectBestAdapter(config);
                var isValid = adapter.ValidateConfig(config);

                var result = new AdapterValidationResult
                {
                    IsValid = isValid,
                    Adapter = adapter,
                    Config = config
                };

                if (isValid)
                {
                    // 测试连接
                    var connectionTest = await adapter.TestConnectionAsync(config);
                    result.ConnectionTest = connectionTest;
                    result.IsValid = connectionTest.Success;
                }

                return result;
            }
            catch (Exception ex)
            {
                return new AdapterValidationResult
                {
                    IsValid = false,
                    ErrorMessage = ex.Message,
                    Config = config
                };
            }
        }

        /// <summary>
        /// 获取注册表实例
        /// </summary>
        /// <returns>注册表实例</returns>
        public ModelAdapterRegistry GetRegistry()
        {
            return _registry;
        }

        /// <summary>
        /// 获取所有适配器的功能描述
        /// </summary>
        /// <returns>功能描述列表</returns>
        public Dictionary<string, AdapterCapabilities> GetAllAdapterCapabilities()
        {
            return _registry.GetAllAdapters()
                .ToDictionary(a => a.Name, a => a.GetCapabilities());
        }
    }

    /// <summary>
    /// 适配器验证结果
    /// </summary>
    public class AdapterValidationResult
    {
        /// <summary>
        /// 是否有效
        /// </summary>
        public bool IsValid { get; set; }

        /// <summary>
        /// 适配器实例
        /// </summary>
        public IModelInvocationAdapter Adapter { get; set; }

        /// <summary>
        /// 配置实例
        /// </summary>
        public ModelInvocationConfig Config { get; set; }

        /// <summary>
        /// 连接测试结果
        /// </summary>
        public ConnectionTestResult ConnectionTest { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// 验证详情
        /// </summary>
        public Dictionary<string, object> Details { get; set; } = new();
    }
}